<template>
  <div class="monitor-container">
    <div class="page-header">
      <div class="page-title">监控告警</div>
    </div>
    
    <div class="page-content">
      <!-- 告警统计卡片 -->
      <div class="alert-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon total-icon">
                  <el-icon><Bell /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">总告警数</div>
                  <div class="stats-card-value">{{ alertStats.total }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon critical-icon">
                  <el-icon><WarningFilled /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">严重告警</div>
                  <div class="stats-card-value">{{ alertStats.critical }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon warning-icon">
                  <el-icon><Warning /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">警告</div>
                  <div class="stats-card-value">{{ alertStats.warning }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-content">
                <div class="stats-card-icon info-icon">
                  <el-icon><InfoFilled /></el-icon>
                </div>
                <div class="stats-card-info">
                  <div class="stats-card-title">信息</div>
                  <div class="stats-card-value">{{ alertStats.info }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 告警规则管理 -->
      <el-card shadow="hover" class="alert-rules-card">
        <template #header>
          <div class="card-header">
            <span>告警规则</span>
            <el-button type="primary" @click="openAddRuleDialog">
              <el-icon><Plus /></el-icon>新增规则
            </el-button>
          </div>
        </template>
        
        <el-table
          v-loading="rulesLoading"
          :data="alertRules"
          border
          style="width: 100%"
        >
          <el-table-column type="index" width="50" align="center" />
          <el-table-column prop="name" label="规则名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="type" label="规则类型" width="120">
            <template #default="{ row }">
              <el-tag>{{ getRuleTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="level" label="告警级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getAlertLevelType(row.level)">
                {{ getAlertLevelText(row.level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="threshold" label="阈值" width="100" />
          <el-table-column prop="task_name" label="关联任务" min-width="150" show-overflow-tooltip />
          <el-table-column prop="notify_type" label="通知方式" width="120">
            <template #default="{ row }">
              <el-tag type="info" v-if="row.notify_type.includes('email')">邮件</el-tag>
              <el-tag type="info" v-if="row.notify_type.includes('sms')" class="ml-5">短信</el-tag>
              <el-tag type="info" v-if="row.notify_type.includes('webhook')" class="ml-5">Webhook</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="editRule(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" link @click="deleteRule(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 告警历史记录 -->
      <el-card shadow="hover" class="alert-history-card">
        <template #header>
          <div class="card-header">
            <span>告警历史</span>
            <div>
              <el-button @click="refreshAlertHistory">
                <el-icon><Refresh /></el-icon>刷新
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table
          v-loading="historyLoading"
          :data="alertHistory"
          border
          style="width: 100%"
        >
          <el-table-column type="index" width="50" align="center" />
          <el-table-column prop="create_time" label="告警时间" min-width="180" show-overflow-tooltip />
          <el-table-column prop="rule_name" label="规则名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="level" label="告警级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getAlertLevelType(row.level)">
                {{ getAlertLevelText(row.level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="task_name" label="关联任务" min-width="150" show-overflow-tooltip />
          <el-table-column prop="message" label="告警内容" min-width="300" show-overflow-tooltip />
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '已处理' : '未处理' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="markAsProcessed(row)" v-if="row.status === 0">
                <el-icon><Check /></el-icon>标记为已处理
              </el-button>
              <el-button type="primary" link @click="viewAlertDetail(row)">
                <el-icon><View /></el-icon>详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-if="historyTotal > 0"
          :current-page="historyQueryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="historyQueryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="historyTotal"
          @size-change="handleHistorySizeChange"
          @current-change="handleHistoryCurrentChange"
          class="pagination"
        />
      </el-card>
      
      <!-- 告警规则对话框 -->
      <el-dialog
        v-model="ruleDialogVisible"
        :title="ruleForm.id ? '编辑告警规则' : '新增告警规则'"
        width="600px"
        destroy-on-close
      >
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="ruleRules"
          label-width="100px"
        >
          <el-form-item label="规则名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
          </el-form-item>
          <el-form-item label="规则类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择规则类型" style="width: 100%">
              <el-option label="任务失败" value="task_failed" />
              <el-option label="任务超时" value="task_timeout" />
              <el-option label="数据量异常" value="data_anomaly" />
              <el-option label="同步延迟" value="sync_delay" />
            </el-select>
          </el-form-item>
          <el-form-item label="告警级别" prop="level">
            <el-select v-model="ruleForm.level" placeholder="请选择告警级别" style="width: 100%">
              <el-option label="严重" value="critical" />
              <el-option label="警告" value="warning" />
              <el-option label="信息" value="info" />
            </el-select>
          </el-form-item>
          <el-form-item label="阈值" prop="threshold" v-if="ruleForm.type !== 'task_failed'">
            <el-input-number v-model="ruleForm.threshold" :min="1" style="width: 100%" />
          </el-form-item>
          <el-form-item label="关联任务" prop="task_id">
            <el-select v-model="ruleForm.task_id" placeholder="请选择关联任务" style="width: 100%">
              <el-option
                v-for="task in taskOptions"
                :key="task.id"
                :label="task.name"
                :value="task.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="通知方式" prop="notify_type">
            <el-checkbox-group v-model="ruleForm.notify_type">
              <el-checkbox label="email">邮件</el-checkbox>
              <el-checkbox label="sms">短信</el-checkbox>
              <el-checkbox label="webhook">Webhook</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="通知对象" prop="notify_target" v-if="ruleForm.notify_type.length > 0">
            <el-input v-model="ruleForm.notify_target" placeholder="请输入通知对象，多个用逗号分隔" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="ruleForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="ruleDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitRuleForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 告警详情对话框 -->
      <el-dialog
        v-model="alertDetailDialogVisible"
        title="告警详情"
        width="600px"
        destroy-on-close
      >
        <el-descriptions :column="1" border>
          <el-descriptions-item label="告警时间">{{ currentAlert.create_time }}</el-descriptions-item>
          <el-descriptions-item label="规则名称">{{ currentAlert.rule_name }}</el-descriptions-item>
          <el-descriptions-item label="告警级别">
            <el-tag :type="getAlertLevelType(currentAlert.level)">
              {{ getAlertLevelText(currentAlert.level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="关联任务">{{ currentAlert.task_name }}</el-descriptions-item>
          <el-descriptions-item label="告警内容">{{ currentAlert.message }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="currentAlert.status === 1 ? 'success' : 'danger'">
              {{ currentAlert.status === 1 ? '已处理' : '未处理' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="currentAlert.process_time">
            {{ currentAlert.process_time }}
          </el-descriptions-item>
          <el-descriptions-item label="处理人" v-if="currentAlert.processor">
            {{ currentAlert.processor }}
          </el-descriptions-item>
          <el-descriptions-item label="处理备注" v-if="currentAlert.process_note">
            {{ currentAlert.process_note }}
          </el-descriptions-item>
        </el-descriptions>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="alertDetailDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="openProcessDialog" v-if="currentAlert.status === 0">
              标记为已处理
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 处理告警对话框 -->
      <el-dialog
        v-model="processDialogVisible"
        title="处理告警"
        width="500px"
        destroy-on-close
      >
        <el-form
          ref="processFormRef"
          :model="processForm"
          :rules="processRules"
          label-width="80px"
        >
          <el-form-item label="处理备注" prop="process_note">
            <el-input
              v-model="processForm.process_note"
              type="textarea"
              :rows="4"
              placeholder="请输入处理备注"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="processDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitProcessForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, WarningFilled, Warning, InfoFilled, Plus, Edit, Delete, Refresh, Check, View } from '@element-plus/icons-vue'
import { getAlertStats, getAlertRules, getAlertHistory, addAlertRule, updateAlertRule, deleteAlertRule, updateAlertStatus, processAlert } from '@/api/monitor'
import { getTaskList } from '@/api/task'

// 告警统计
const alertStats = ref({
  total: 0,
  critical: 0,
  warning: 0,
  info: 0
})

// 告警规则
const rulesLoading = ref(false)
const alertRules = ref([])

// 告警历史
const historyLoading = ref(false)
const alertHistory = ref([])
const historyTotal = ref(0)
const historyQueryParams = reactive({
  page: 1,
  size: 10
})

// 对话框
const ruleDialogVisible = ref(false)
const alertDetailDialogVisible = ref(false)
const processDialogVisible = ref(false)

// 表单
const ruleFormRef = ref(null)
const processFormRef = ref(null)
const ruleForm = reactive({
  id: '',
  name: '',
  type: '',
  level: '',
  threshold: 1,
  task_id: '',
  task_name: '',
  notify_type: [],
  notify_target: '',
  status: 1
})
const processForm = reactive({
  id: '',
  process_note: ''
})

// 表单校验规则
const ruleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择告警级别', trigger: 'change' }
  ],
  task_id: [
    { required: true, message: '请选择关联任务', trigger: 'change' }
  ],
  notify_type: [
    { required: true, message: '请选择通知方式', trigger: 'change' }
  ],
  notify_target: [
    { required: true, message: '请输入通知对象', trigger: 'blur' }
  ]
}
const processRules = {
  process_note: [
    { required: true, message: '请输入处理备注', trigger: 'blur' }
  ]
}

// 任务选项
const taskOptions = ref([])

// 当前告警
const currentAlert = ref({})

// 获取规则类型文本
const getRuleTypeText = (type) => {
  const typeMap = {
    'task_failed': '任务失败',
    'task_timeout': '任务超时',
    'data_anomaly': '数据量异常',
    'sync_delay': '同步延迟'
  }
  return typeMap[type] || '未知'
}

// 获取告警级别类型
const getAlertLevelType = (level) => {
  const levelMap = {
    'critical': 'danger',
    'warning': 'warning',
    'info': 'info'
  }
  return levelMap[level] || 'info'
}

// 获取告警级别文本
const getAlertLevelText = (level) => {
  const levelMap = {
    'critical': '严重',
    'warning': '警告',
    'info': '信息'
  }
  return levelMap[level] || '未知'
}

// 获取告警统计
const getStats = async () => {
  try {
    const res = await getAlertStats()
    alertStats.value = res.data
  } catch (error) {
    console.error('获取告警统计失败:', error)
  }
}

// 获取告警规则列表
const getRules = async () => {
  rulesLoading.value = true
  try {
    const res = await getAlertRules()
    alertRules.value = res.data
  } catch (error) {
    console.error('获取告警规则列表失败:', error)
  } finally {
    rulesLoading.value = false
  }
}

// 获取告警历史列表
const getHistory = async () => {
  historyLoading.value = true
  try {
    const res = await getAlertHistory(historyQueryParams)
    alertHistory.value = res.data
    historyTotal.value = res.total
  } catch (error) {
    console.error('获取告警历史列表失败:', error)
  } finally {
    historyLoading.value = false
  }
}

// 获取任务列表
const getTasks = async () => {
  try {
    const res = await getTaskList({ page: 1, size: 1000 })
    taskOptions.value = res.data
  } catch (error) {
    console.error('获取任务列表失败:', error)
  }
}

// 打开新增规则对话框
const openAddRuleDialog = () => {
  Object.keys(ruleForm).forEach(key => {
    if (key === 'status') {
      ruleForm[key] = 1
    } else if (key === 'threshold') {
      ruleForm[key] = 1
    } else if (key === 'notify_type') {
      ruleForm[key] = []
    } else {
      ruleForm[key] = ''
    }
  })
  ruleDialogVisible.value = true
}

// 编辑规则
const editRule = (row) => {
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = row[key]
  })
  ruleDialogVisible.value = true
}

// 删除规则
const deleteRule = (row) => {
  ElMessageBox.confirm('确认删除该告警规则吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAlertRule(row.id)
      ElMessage.success('删除成功')
      getRules()
    } catch (error) {
      console.error('删除告警规则失败:', error)
    }
  }).catch(() => {})
}

// 提交规则表单
const submitRuleForm = async () => {
  if (!ruleFormRef.value) return
  
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (ruleForm.id) {
          await updateAlertRule(ruleForm)
          ElMessage.success('更新成功')
        } else {
          await addAlertRule(ruleForm)
          ElMessage.success('添加成功')
        }
        ruleDialogVisible.value = false
        getRules()
      } catch (error) {
        console.error('保存告警规则失败:', error)
      }
    }
  })
}

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    await updateAlertStatus(row.id, { status: row.status })
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 刷新告警历史
const refreshAlertHistory = () => {
  getHistory()
}

// 查看告警详情
const viewAlertDetail = (row) => {
  currentAlert.value = row
  alertDetailDialogVisible.value = true
}

// 标记为已处理
const markAsProcessed = (row) => {
  currentAlert.value = row
  openProcessDialog()
}

// 打开处理对话框
const openProcessDialog = () => {
  processForm.id = currentAlert.value.id
  processForm.process_note = ''
  processDialogVisible.value = true
}

// 提交处理表单
const submitProcessForm = async () => {
  if (!processFormRef.value) return
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await processAlert(processForm)
        ElMessage.success('处理成功')
        processDialogVisible.value = false
        alertDetailDialogVisible.value = false
        getHistory()
        getStats()
      } catch (error) {
        console.error('处理告警失败:', error)
      }
    }
  })
}

// 每页数量变化
const handleHistorySizeChange = (size) => {
  historyQueryParams.size = size
  getHistory()
}

// 当前页变化
const handleHistoryCurrentChange = (page) => {
  historyQueryParams.page = page
  getHistory()
}

onMounted(() => {
  getStats()
  getRules()
  getHistory()
  getTasks()
})
</script>

<style lang="scss" scoped>
.monitor-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .page-title {
      font-size: 20px;
      font-weight: bold;
    }
  }
  
  .page-content {
    .alert-stats {
      margin-bottom: 20px;
      
      .stats-card {
        height: 120px;
        
        .stats-card-content {
          display: flex;
          align-items: center;
          height: 100%;
          
          .stats-card-icon {
            width: 64px;
            height: 64px;
            border-radius: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 16px;
            
            .el-icon {
              font-size: 32px;
              color: #fff;
            }
            
            &.total-icon {
              background-color: #409EFF;
            }
            
            &.critical-icon {
              background-color: #F56C6C;
            }
            
            &.warning-icon {
              background-color: #E6A23C;
            }
            
            &.info-icon {
              background-color: #909399;
            }
          }
          
          .stats-card-info {
            .stats-card-title {
              font-size: 14px;
              color: #909399;
              margin-bottom: 8px;
            }
            
            .stats-card-value {
              font-size: 24px;
              font-weight: bold;
              color: #303133;
            }
          }
        }
      }
    }
    
    .alert-rules-card {
      margin-bottom: 20px;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
    
    .ml-5 {
      margin-left: 5px;
    }
  }
}
</style>